let _Vue = null
export default class VueRouter{
  static install (Vue){
    // 判断是否已安装
    if(VueRouter.install.installed){
      return 
    }
    VueRouter.install.installed = true
    // 吧Vue构造函数记录到全局变量
    _Vue = Vue
    // 吧创建Vue实例时候传入的routet对象注入到Vue实例上
    // 混入
    _Vue.mixin({
      beforCreate(){
        if(this.$options.router){
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })

  }

  constructor(options){
    this.options = options
    this.routeMap = {}
    this.mode = options.mode || 'hash'
    this.data = _Vue.observable({
      current:'/'
    })
  }

  init(){
    this.createRouteMap()
    if(this.mode === 'history'){
      this.initComponents(_Vue)
      this.initEvent()
    }else{
      this.initHashComponents(_Vue)
      this.initHashEvent()
    }
  }

  createRouteMap(){
    // 遍历所有的路由规则，吧路由规则解析成键值对的形式
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }
  initHashComponents(Vue){
    Vue.component('router-link',{
      props:{
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>'
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler(e) {
          location.hash = this.to
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })
    const self = this
    Vue.component('router-view', {
      render(h) {
        const com = self.routeMap[self.data.current]
        return h(com)
      }
    })
  }
  initHashEvent(){
    window.addEventListener('hashchange', () => {
      this.data.current = location.hash.slice(1)
    })
  }
  initComponents (Vue) {
    Vue.component('router-link',{
      props:{
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>'
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler(e) {
          history.pushState({}, '', this.to)
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })
    const self = this
    Vue.component('router-view', {
      render(h) {
        const com = self.routeMap[self.data.current]
        return h(com)
      }
    })
  }

  initEvent() {
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname
    })
  }
}